<template>
	<view v-if="formData.status != undefined">
		<uni-notice-bar
		:background-color="useStateFormat.bgColor"
		:color="useStateFormat.color" 
		showIcon 
		:text="noticeText"></uni-notice-bar>
	</view>
	
	<view class="editLayout">
		<view class="row">
			<view class="head">
				<view class="title">
					发布类型<text class="required">*</text>
				</view>				
			</view>
			<view class="body">
				<radio-group @change="radioChange">					
					<label class="radio">
						<radio :disabled="disabled || statusDisabled" value="0" color="#4F9153" :checked="formData.trip_type==0"></radio>车找人
					</label>
					<label class="radio">
						<radio :disabled="disabled || statusDisabled" value="1" color="#f83162" :checked="formData.trip_type==1"></radio>人找车
					</label>
				</radio-group>
			</view>
		</view>
		
		<view class="row">
			<datetime-select title="出发时间" @selectDate="onSelectDate"
				@selectStartTime="onSelectStartTime" @selectEndTime="onSelectEndTime">
			 </datetime-select>
		</view>
		<view class="row">
			<location-item title="起点" 
			@selectArea="onSelectFromArea" @selectDetail="onSelectFromDetail"></location-item>
			
		</view>
		<view class="row">
			<location-item title="终点" @selectArea="onSelectToArea" @selectDetail="onSelectToDetail"></location-item>			
		</view>
	
		<view class="row">
			<view class="head">
				<view class="title">行程要求</view>
				<text class="subTitle">
					给对方的留言，不超过一行
				</text>
			</view>
			<view class="body">
				<textarea :disabled="disabled || statusDisabled" 
				rows="2"
				maxlength="20"
				v-model="formData.content" 
				class="content" placeholder="补充行程说明~~">
				</textarea>
			</view>
		</view>
		
		<view class="row">
			<view class="head">
				<view class="title">
					行程报价参考<text class="required">*</text>
				</view>
				<text class="subTitle" v-if="!formData.trip_type">
					1. 此数值为车主发布的预估报价；\n2. 为了避免争议，请上车前务必确认最终行程费用；
				</text>

				<text class="subTitle" v-else="formData.trip_type">
					1.此数值为乘客期望同行的预估报价；\n2.为了避免争议，请上车前务必确认最终行程费用;\n
				</text>
			</view>
			<view class="body">
				<uni-number-box :min="0" :max="30" :value="formData.predict_price"  @change="onPriceChange"/>
			</view>
		</view>
		
		
		<view class="row" v-if="!formData.trip_type">
			<file-upload @uploadFileUrl="onUploadFileUrl"></file-upload>
		</view>
		
		
		<view class="row btnGroup">			
			<view class="body">
				<button type="primary" @click="onSubmit" :disabled="statusDisabled || disabled">提交审核</button>
			</view>
		</view>
		
	</view>
</template>

<script setup>
import { ref,computed } from 'vue';
import {showToast,stateFormat,getTimestampByStr,getCurrent, getRegionInfo} from "@/utils/common.js"
import {removeHtmlTags} from "@/utils/tools.js"
import {onLoad} from "@dcloudio/uni-app"


const useStateFormat =  computed(()=>stateFormat(formData.value.status));

const db = uniCloud.database();
const id = ref("")
// onLoad是页面加载时的生命周期函数，它接收一个参数 e，这个参数包含了页面跳转时传递的所有参数
// onLoad方法放在变量声明之前
onLoad((e)=>{
	id.value = e.id
	if(id.value){
		uni.showLoading({
			title:"加载中...",
			mask:true
		})
		getDetail();
		uni.setNavigationBarTitle({
			title:"编辑行程"
		})
	}
})


const formData = ref({
	trip_type:0,
	content:"",
	from_region:"广东省广州市天河区",
	from_detail:"凯华国际东门",
	to_region:"广东省广州市增城区",
	to_detail:"凤岗地铁站C口",
	start_time: Date.now(),
	end_time: Date.now(),
	map_url:"",
	predict_price:10
})
const disabled = ref(false);
const statusDisabled = ref(false);
const date = ref(getCurrent('date'))
const start_time = ref(getCurrent('time'))
const end_time = ref(getCurrent('time'))

// :province="from_province" :city="from_city" :area="from_area"
// const from_province = computed(()=>{
// 	// console.log(formData.value.from_region);
// 	return getRegionInfo(formData.value.from_region, "province")
// })

// const from_city = computed(()=>{
// 	return getRegionInfo(formData.value.from_region, "city")
// })

// const from_area = computed(()=>{
// 	return getRegionInfo(formData.value.from_region, "area")
// })


const onSubmit = async ()=>{
	try{
		disabled.value = true;
		uni.showLoading({
			title:"提交中"
		})
		formData.value.content = removeHtmlTags(formData.value.content);	
		
		if(formData.value.from_region==="" || formData.value.from_detail==="" || formData.value.to_region ===""
				|| formData.value.to_detail===""){
			return showToast('地址不能为空',"none",false)
		}
		// todo 等待恢复
		// if(formData.value.predict_price ==="0" || !formData.value.predict_price){
		// 	// console.log("报价：",formData.value.predict_price);
		// 	return showToast('报价不能为空',"none",false)
		// }	
		
		// const mix_start_time = Date.now() + 5 * 60 * 1000
		// if(formData.value.start_time <= mix_start_time){
		// 	// console.log("行程时间：", formData.value.start_time, mix_start_time);
		// 	return showToast('当前距离起始时间太近',"none",false)
		// }	
		
		// if(formData.value.start_time >= formData.value.end_time){
		// 	console.log("行程时间：",formData.value.start_time, formData.value.end_time);
		// 	return showToast('行程结束时间应大于起始时间',"none",false)
		// }
	
			
		let errCode,res
		let {
			trip_type, status, content, from_region, from_detail, to_region, to_detail, 
			start_time, end_time, predict_price, map_url
		} = formData.value;
		let _formData = {
			trip_type, content, status:0, from_region, from_detail, to_region, to_detail, 
			start_time, end_time, predict_price, map_url, last_modify_date:Date.now()
			
		};

		if(id.value){	
			console.log("更新");
			// 更新
			res = await db.collection("trip-detail").doc(id.value).update(_formData);			
		}else{
			console.log("插入");
			// 插入
			formData.value.status = 1 // todo test
			res = await db.collection("trip-detail").add(formData.value);
		}		
		errCode = res.result.errCode;
				
		console.log(res, errCode);
		// if(errCode === 0){
		// 	uni.$emit("tripUpdate",{msg:"更新了"});		// 发布行程更新事件
		// 	showToast("发表成功","success");	
		// 	setTimeout(()=>uni.navigateBack(),1000)			
		// }	
		uni.$emit("tripUpdate",{msg:"更新了"});		// 发布行程更新事件
		showToast("发表成功","success");	
		setTimeout(()=>uni.navigateBack(),1000)		
	}catch(e){		
		showToast(e.errMsg,"error")
	}finally{
		uni.hideLoading();
		disabled.value = false;
	}	
}


//获取单条数据
const getDetail = async()=>{
	// console.log("id: ", id.value);
	let {result:{errCode,data}} = await db.collection("trip-detail").where({_id:id.value}).get({
		getOne:true
	});
	// console.log("getDetail: ", data);
	if(errCode === 0){
		formData.value = data
		if(formData.value.status !==2) statusDisabled.value = true;
	}
	uni.hideLoading()
}

const noticeText = computed(() => {
    const status = formData.value.status;
    const baseText = `通知：${useStateFormat.value.text}`;
    
    if (status === 0 || status === 1) {
        return `${baseText}，不允许再次编辑。`;
    } else {
        // 只有当 feedback 存在时才添加相关文本
        return formData.value.feedback 
            ? `${baseText}，${formData.value.feedback}，修改后可再次提交。`
            : `${baseText}，修改后可再次提交。`;
    }
});

// 文件上传完成
const onUploadFileUrl = (e)=>{
	formData.value.map_url = e
}

// 设置行程日期
const onSelectDate = (e) =>{
	date.value = e
	start_time.value = getTimestampByStr(date.value, start_time.value);
	formData.value.start_time = start_time.value;
	end_time.value = getTimestampByStr(date.value, end_time.value);
	formData.value.end_time = end_time.value;
}

const onSelectStartTime = (e) =>{	
	start_time.value = getTimestampByStr(date.value, e);
	formData.value.start_time = start_time.value;
}

const onSelectEndTime = (e) =>{	
	end_time.value = getTimestampByStr(date.value, e);
	formData.value.end_time = end_time.value;
}

// 设置起点的地区
const onSelectFromArea = (e) =>{
	formData.value.from_region = e;
}
//设置起点的详情
const onSelectFromDetail = (e) =>{
	formData.value.from_detail = e;
}
//设置终点的地区
const onSelectToArea = (e) =>{
	formData.value.to_region = e;
}
//设置终点的详情
const onSelectToDetail = (e) =>{
	formData.value.to_detail = e;
}

const onPriceChange = (value)=>{
	formData.value.predict_price = value;
}

// 切换发布类型
const radioChange = (e)=>{	
	formData.value.trip_type = Number(e.detail.value);
}

</script>

<style lang="scss" scoped>
.editLayout{
	padding:30rpx;
	.row{
		padding-bottom:10rpx;
		.head{
			// padding-bottom:10rpx;
			.title{
				font-size: 34rpx;
				padding-left:20rpx;
				position: relative;
				padding-bottom:6rpx;
				.required{
					color: #f00;
					margin-left: 4rpx;
				}
				&::before{
					content: "";
					display: block;
					width: 8rpx;
					height: 30rpx;
					background: $brand-theme-color;
					position: absolute;
					left:0;
					top:calc(50% - 15rpx);
					border-radius: 10rpx;
				}
			}
			.subTitle{
				display: block;
				color: #666;
				font-size: 24rpx;
				line-height: 1.5;      /* 控制行间距 */
				white-space: pre-line; /* 保留换行符 */
				padding: 0 20rpx;      /* 左右内边距 */
				text-align: left;      /* 文本左对齐 */
			}
		}
		.body{
			margin-left: 20rpx;
			padding: 5rpx 10rpx 5rpx 0;
			font-size:  $text-font-size-input;
			.radio{
				margin-right:30rpx;
				radio{
					transform: scale(0.9);
				}
			}
			.content{
				border: 1px solid $border-color;
				width: 100%;
				height: 60rpx;
				background: #f3f3f3;
				border-radius: 10rpx;
				overflow: hidden; /* 隐藏超出文本区域的内容 */
				padding: 10rpx 20rpx; /* 添加内边距 */
				box-sizing: border-box; /* 包含内边距和边框在内的总宽度和高度 */
			
				/* 文本相关设置 */
				line-height: 40rpx; /* 行高等于容器高度 */
				min-height: 40rpx; /* 确保最小高度 */
				resize: none; /* 禁止调整大小 */
				

			}
			// /* 设置 placeholder 的样式 */
			.content::placeholder {
				line-height: 40rpx; /* 设置与容器相同的行高 */
				padding-left: 20rpx; /* 左侧内边距 */
			}
		}
	}
	
	.btnGroup{
		padding-top:60rpx;
	}
}

[disabled]:not(button){
	color:#bbb;
}
</style>
